package cn.edu.scau.cmi.liangguan.database.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.scau.cmi.liangguan.database.DAO.StudentDAO;
import cn.edu.scau.cmi.liangguan.database.DAO.TutorDAO;
import cn.edu.scau.cmi.liangguan.database.domain.Student;
import cn.edu.scau.cmi.liangguan.database.domain.Tutor;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class DBServlet
 */
@WebServlet("/DBServlet")
public class DBServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DBServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/json;charset=GBK");
		
		PrintWriter out = response.getWriter();
    
		String op = request.getParameter("op");
		JSONArray jsonArray = null;
		if (op.compareTo("1")==0) {
			StudentDAO studentDAO = new StudentDAO();
			ArrayList<Student> list = studentDAO.getAllStudents();
			jsonArray  = JSONArray.fromObject(list);
			out.println(jsonArray);	
		}else {
			TutorDAO tutorDAO = new TutorDAO();
			ArrayList<Tutor> list = tutorDAO.getAllTutors();
			jsonArray = JSONArray.fromObject(list);
			out.println(jsonArray);
		}
	}

	protected void error(PrintWriter out) {
		String error = "[{'error':'true'}]";
		JSONArray jsonArray = JSONArray.fromObject(error);
		out.println(jsonArray);			
	}
}
